package com.cskaoyan.util;

import com.cskaoyan.bean.po.MarketUser;
import com.cskaoyan.config.exception.LoginAuthenException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @author chenai
 * @description TODO
 * @date 2022-06-08 14:55
 */
public class UserIdUtil {
    //如果认证失败返回-1，在Controller中返回BaseRespVo.invalidData("请先登录")
    //如果认证成功返回userId
    public static Integer getUserIdFromSubject() {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            return -1;
        }
        MarketUser principal = ((MarketUser) subject.getPrincipals().getPrimaryPrincipal());
        Integer userId = principal.getId();
        return userId;
    }

    public static Integer getUserIdFromSubjectThrowException() throws LoginAuthenException {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {

            throw new LoginAuthenException();
        }
        MarketUser principal = ((MarketUser) subject.getPrincipals().getPrimaryPrincipal());
        Integer userId = principal.getId();
        return userId;
    }

}
